<template>
  <el-form ref="form" label-width="80px">
    <el-form-item label="头像">
      <div class="avatar-div">
        <img v-show="form.avatar" :src="form.avatar" class="avatar"/>
        <el-upload
          action="http://localhost:3000/upload/img"
          name="myfile"
          :show-file-list="false"
          :headers="uploadHeaders"
          :on-success="handleAvatarSuccess"
        >
          <el-button>上传</el-button>
        </el-upload>
      </div>
    </el-form-item>
    <el-form-item label="用户名">
      <el-col :span="6">
        <el-input v-model="form.username" disabled placeholder="请输入用户名"></el-input>
      </el-col>
    </el-form-item>
    <el-form-item label="性别">
      <el-radio v-model="form.sex" label="男">男</el-radio>
      <el-radio v-model="form.sex" label="女">女</el-radio>
      <el-radio v-model="form.sex" label="保密">保密</el-radio>
    </el-form-item>
    <el-form-item label="个人简介">
      <el-col :span="6">
        <el-input type="textarea" v-model="form.desc" rows="3" placeholder="填写你的个人简介"></el-input>
      </el-col>
    </el-form-item>
    <el-form-item label="手机号">
      <el-col :span="6">
        <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
      </el-col>
    </el-form-item>
    <el-form-item label="电子邮箱">
      <el-col :span="6">
        <el-input v-model="form.email" placeholder="请输入电子邮箱"></el-input>
      </el-col>
    </el-form-item>
    <el-form-item>
      <el-button type="success" round @click="handleClickButtonSave">更新</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
  import Cache from '@/cache'
  import axios from 'axios'

  export default {
    data() {
      return {
        imageUrl: '',
        uploadHeaders: {},
        form: {
          _id: '',
          username: '',
          avatar: '',
          sex: '男',
          desc: '',
          phone: '',
          email: ''
        }
      }
    },
    created() {
      this.form = this.$store.state.user
      const user = Cache.get('USER') || {token: ''}
      this.uploadHeaders = {authorization: `Bearer ${user.token}`}
    },
    methods: {
      handleAvatarSuccess(res, file) {
        this.form.avatar = res.data
      },
      handleClickButtonSave() {
        this
          .$http({
            path: '/users/update/personal',
            method: 'post',
            params: this.form
          })
          .then(res => {
            const {code, msg} = res.data
            console.log('res', res)
            this.$message({
              message: msg,
              type: code === 200 ? 'success' : 'error'
            })
          })
      }
    }
  }
</script>

<style>
  .avatar-div {
    display: flex;
    align-items: center;
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
    margin-right: 20px;
  }
</style>
